#########################################################################
# File Name:    rootfs.sh
# Author:       ChenBlue
# mail:         ChenBlue952@qq.com
# Created Time: 2024年11月09日 星期六 10时56分09秒
#########################################################################
#!/bin/bash

ARCH=$1

#1. 安装要用到的软件
if ! which debootstrap >/dev/null 2>&1 ; then
	echo "没有 debootstrap 这个工具, 正在安装"
	sudo apt install qemu-user-static debootstrap
fi

#2. 拉取基本的rootfs
sudo debootstrap --foreign --verbose --arch=${ARCH} bookworm rootfs http://mirrors.tuna.tsinghua.edu.cn/debian/

#3. 将模拟器放进去
sudo cp /usr/bin/qemu-aarch64-static rootfs/usr/bin/
sudo chmod +x rootfs/usr/bin/qemu-aarch64-static

#4. 挂载动态文件
cd rootfs
sudo mount --bind /dev dev/
sudo mount --bind /sys sys/
sudo mount --bind /proc proc/
sudo mount --bind /dev/pts dev/pts/
cd ..

#5. 完成剩余的构建过程
sudo LC_ALL=C LANGUAGE=C LANG=C chroot rootfs /debootstrap/debootstrap --second-stage --verbose

#6. 进入文件系统安装一些必要的软件和配置
echo -e "\033[47;36m Change root.....................\033[0m"
cat << EOF | sudo chroot rootfs

export LC_ALL=C.UTF-8

apt-get update
apt-get upgrade -y

#export APT_INSTALL="apt-get install -fy --allow-downgrades"

passwd root <<IEOF
yckj
yckj
IEOF

echo "yckj" > /etc/hostname

# set localtime
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
apt install systemd-timesyncd
echo -e "y" | apt install ssh parted net-tools network-manager

# 修改 SSH 配置文件，允许 root 登录
echo "修改 /etc/ssh/sshd_config 文件，允许 root 登录..."
sed -i 's/^#PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config

exit
EOF

#7. 解除动态文件的挂载
cd rootfs
sudo umount   sys/
sudo umount   proc/
sudo umount   dev/pts/
sudo umount   dev/
cd ..

#8. 将一些 文件夹改成普通权限
sudo chmod 644 rootfs/var/log/private
sudo chmod 644 rootfs/var/spool/cron/crontabs
sudo chmod 644 rootfs/var/lib/private
sudo chmod 644 rootfs/var/lib/apt/lists/partial
sudo chmod 644 rootfs/var/cache/private
sudo chmod 755 rootfs/var/cache/ldconfig
sudo chmod 644 rootfs/var/cache/apt/archives/partial
sudo chmod 644 rootfs/var/cache/ldconfig/aux-cache
sudo chmod 644 rootfs/var/cache/apt/archives/partial
sudo chmod 755 rootfs/var/cache/ldconfig/aux-cache
sudo chmod 755 rootfs/root
sudo chmod 755 rootfs/root/.ssh
sudo chmod 644 rootfs/etc/ssh/ssh_host*
sudo chmod 644 rootfs/etc/shadow*
sudo chmod 644 rootfs/etc/gshadow*

#9. 去除一些不重要的又影响打包的东西
sudo rm -rf `find rootfs -name private`
sudo rm -rf `find rootfs -name crontabs`
sudo rm -rf `find rootfs -name partial`


cp -r rootfs debian-$ARCH >/dev/null 2>&1
sudo rm -rf rootfs
